package com.yonyou.pmclouds.measureindex.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.BuziExCodeConst;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.measureindex.entity.MeasureIndexVO;
import com.yonyou.pmclouds.measureindex.mapper.MeasureIndexMapper;
import org.apache.commons.lang3.StringUtils;

public class MeasureIndexNameAndCodeCheck implements SingleProcessor<MeasureIndexVO> {
    private MeasureIndexMapper mapper;

    public MeasureIndexNameAndCodeCheck(MeasureIndexMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void process(MeasureIndexVO vo, MeasureIndexVO orig) throws BusinessException {

        String tenantId = RuntimeEnvironment.getTenantId();
        boolean codeUnique = mapper.countCode(vo.getCode(),tenantId) == 0;
        boolean nameUnique = mapper.countName(vo.getName(),tenantId) == 0;

        if (orig == null) {
            if (!codeUnique && !nameUnique) {
                throw new BusinessException("已经存在相同的编码'"+vo.getCode()+"'、名称'"+vo.getName()+"'，请修改!", BuziExCodeConst.CODE_NAME_CODE_DUPLICATE);
            }
            //校验编码
            if (!codeUnique) {
                throw new BusinessException("已经存在相同的编码'"+vo.getCode()+"'，请修改!", BuziExCodeConst.CODE_CODE_DUPLICATE);
            }
            //校验名字
            if (!nameUnique) {
                throw new BusinessException("已经存在相同的名称'"+vo.getName()+"'，请修改!", BuziExCodeConst.CODE_NAME_DUPLICATE);
            }

        } else {

            if(vo.getName().equals(orig.getName()) && vo.getCode().equals(orig.getCode())){
                return;
            }
            if(vo.getName().equals(orig.getName())){
                //判断编码是否存在
                //校验编码
                if (!codeUnique) {
                    throw new BusinessException("已经存在相同的编码'"+vo.getCode()+"'，请修改!", BuziExCodeConst.CODE_CODE_DUPLICATE);
                }
            }
            if(vo.getCode().equals(orig.getCode())){
                //校验名字
                if (!nameUnique) {
                    throw new BusinessException("已经存在相同的名称'"+vo.getName()+"'，请修改!", BuziExCodeConst.CODE_NAME_DUPLICATE);
                }
            }
            if (!codeUnique && !nameUnique) {
                throw new BusinessException("已经存在相同的编码'"+vo.getCode()+"'、名称'"+vo.getName()+"'，请修改!", BuziExCodeConst.CODE_NAME_CODE_DUPLICATE);
            }
        }
    }
}
